import React from 'react';
import clsx from 'clsx';
import { Photo, PhotoFail } from '../icons';
import Image from './Image';
import { Lazyload } from '../lazyload';
import { LazyImageProps } from './PropsType';
import { COMPONENT_TYPE_KEY } from '../utils/constant';
import { BEM } from '../utils/create/bem';
import useNamespace from '../utils/useNamespace';

export const getLazyImagePlaceholder = (bem: BEM): React.ReactElement => (
  <div className={clsx(bem('loading'))}>
    <Photo className={clsx(bem('loading-icon'))} />
  </div>
);

const LazyImage: React.FC<LazyImageProps> = ({
  lazyload,
  fit = 'fill',
  errorIcon = <PhotoFail />,
  loadingIcon = <Photo />,
  showError = true,
  showLoading = true,
  block = true,
  ...rest
}) => {
  const [bem] = useNamespace('image');
  const imageProps = { fit, errorIcon, loadingIcon, showError, showLoading, block, ...rest };
  const renderPlaceholder = () => {
    if (!lazyload) {
      return getLazyImagePlaceholder(bem);
    }
    if (typeof lazyload === 'boolean') return getLazyImagePlaceholder(bem);
    return lazyload.placeholder || getLazyImagePlaceholder(bem);
  };

  if (lazyload) {
    const { className, style, height, width } = imageProps;
    const attrs = {
      className: clsx(className, bem({ block: imageProps.block })),
      style: { ...style, height, width },
    };
    return (
      <Lazyload {...attrs} placeholder={renderPlaceholder()}>
        <Image {...imageProps} />
      </Lazyload>
    );
  }
  return <Image {...imageProps} />;
};

export const IMAGE_KEY = Symbol('image');
const ImageNamespace = Object.assign(LazyImage, { [COMPONENT_TYPE_KEY]: IMAGE_KEY });

export default ImageNamespace;
